<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\Login as ModelLogin;

/**
 * 注册接口
 */
class Register extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 注册处理
     */
    public function regdata()
    {
        // 获取 token
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
        if ($token) {
            $this->error('请勿重复注册');
        }
        $username = $this->request->post("username", '', 'trim');
        $password = $this->request->post("password", '', 'trim');
        $mobile   = $this->request->post("mobile", '', 'trim');
        if (empty($username)) {
            $this->error('用户名不能为空');
        }
        if (empty($password)) {
            $this->error('密码不能为空');
        }
        if (empty($mobile)) {
            $this->error('手机号不能为空');
        }
        // 判断手机号格式是否正确
        $mobilereg = "/^1[3456789]\d{9}$/";
        if (!preg_match($mobilereg, $mobile)) {
            $this->error('手机号格式不正确');
        }
        // 判断唯一：手机号唯一、用户名唯一
        $isexisMobile = ModelLogin::where('mobile', $mobile)->find();
        if ($isexisMobile) {
            $this->error('手机号已被注册');
        }
        $isexisName = ModelLogin::where('username', $username)->find();
        if ($isexisName) {
            $this->error('用户名已被注册');
        }

        $memdata = [
            'username' => $username,
            'password' => md5($password),
            'mobile'   => $mobile,
        ];
        $res = ModelLogin::create($memdata);
        if ($res !== false) {
            $this->success("注册成功");
        } else {
            $this->error("注册失败,请重新注册");
        }
    }
}
